<template>
  <div>
    <el-card>
      <div slot="header">
        <div class="flex-x gap-4 pt-2">
          <span>
            <vxe-input v-model="query.keyword" :placeholder="'搜索课程名称'" size="medium" clearable
              @keyup.enter.native="filterByKeyword"></vxe-input>
          </span>
          <span>
            <el-button type="primary" plain size="small" @click="filterByKeyword" icon="el-icon-search"
              :loading="loading">搜索</el-button>
          </span>
          <span class="flex-1"></span>
          <span>
            <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">
              添加课程
            </el-button>
          </span>
        </div>
      </div>

      <!-- Course Table -->
      <vxe-table stripe auto-resize :data="dataList" :loading="loading" :custom-config="tableCustomConfig"
                 align="center" ref="table">
        <vxe-table-column field="id" title="ID" width="60"></vxe-table-column>
        <vxe-table-column field="courseName" title="课程名称" min-width="120" align="left">
          <template v-slot="{ row }">
            <div class="flex-y justify-center items-start gap-2">
              <el-image style="width: 60px" :src="row.listImage" :preview-src-list="[row.listImage]" fit="cover">
              <div slot="error">
                <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <span class="font-12">{{ row.courseName }}</span>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="description" title="课程简介" min-width="200" show-overflow></vxe-table-column>
        <vxe-table-column field="tags" title="标签" min-width="200">
          <template v-slot="{ row }">
            <div class="flex-x flex-center flex-wrap gap-2">
              <el-tag v-for="tag in row.tags" :key="tag.id" size="small">{{ tag.name }}</el-tag>
              <el-button type="text" size="medium" :icon="`el-icon-${row.tags?.length > 0 ? 'edit' : 'plus'}`" @click="handleEditTags(row)"></el-button>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column title="详情页图片" :visible="false">
          <template v-slot="{ row }">
            <el-image style="width: 60px" :src="row.detailImage" :preview-src-list="[row.detailImage]" fit="cover">
              <div slot="error">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </vxe-table-column>
        <vxe-table-column field="hours" title="课时" min-width="60"></vxe-table-column>

        <vxe-table-column title="状态" width="180">
          <template v-slot:header>
            <div class="flex-x flex-center gap-2">
              <span>状态</span>
              <el-tooltip effect="light" content="发布后学生可见，公开后全平台可见，分享后平台其他学校可复制" placement="top">
                <i class="fa fa-question-circle-o font-14"></i>
              </el-tooltip>
            </div>
          </template>
          <template v-slot="{ row }">
            <div class="flex-x flex-center gap-2">
              <div class="flex-y flex-center">
                <el-switch v-model="row.enabled" @change="handleStatusChange(row, 'enabled')" class="my-2"></el-switch>
                <span class="font-10">{{ row.enabled ? '已发布' : '编辑中' }}</span>
              </div>
              <div class="flex-y flex-center">
                <el-switch v-model="row.isPublic" @change="handleStatusChange(row, 'isPublic')"
                  class="my-2"></el-switch>
                <span class="font-10">{{ row.isPublic ? '公开' : '私密' }}</span>
              </div>
              <div class="flex-y flex-center">
                <el-switch v-model="row.isShare" @change="handleStatusChange(row, 'isShare')"
                  class="my-2"></el-switch>
                <span class="font-10">{{ row.isShare ? '分享中' : '未分享' }}</span>
              </div>
            </div>
          </template>
        </vxe-table-column>

        <vxe-table-column field="gmtCreate" title="创建时间" width="150">
          <template v-slot="{ row }">
            {{ formatDate(row.gmtCreate) }}
          </template>
        </vxe-table-column>
        <vxe-table-column title="操作" width="150" fixed="right">
          <template v-slot="{ row }">
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button plain circle type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button plain circle type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="章节管理" placement="top">
              <el-button plain circle type="success" size="mini" icon="el-icon-s-operation"
                @click="handleManageSections(row)">
              </el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
      </vxe-table>

      <!-- Pagination -->
      <div class="flex-x justify-end mt-4 gap-4">
        <el-pagination class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="query.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
        <el-button type="plain" size="mini" @click="handleTableCustom" circle icon="el-icon-menu"></el-button>
      </div>

      <!-- Course Dialog -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%" @close="resetForm">
        <el-form :model="formData" :rules="rules" ref="courseForm" label-width="100px">
          <el-form-item label="课程名称" prop="courseName">
            <el-input v-model="formData.courseName"></el-input>
          </el-form-item>
          <el-form-item label="课程简介" prop="description">
            <Editor :value.sync="formData.description"></Editor>
          </el-form-item>

          <div class="flex-x">
            <el-form-item label="列表页图片" prop="listImage" class="flex-1">
              <div style="width: 120px;">
                <el-upload class="avatar-uploader" action="/api/file/upload-course-img" :show-file-list="false"
                  accept="image/jpeg,image/png,image/webp" :on-success="(res) => handleUploadSuccess(res, 'listImage')"
                  :before-upload="beforeUpload">
                  <img v-if="formData.listImage" :src="formData.listImage" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </el-form-item>

            <el-form-item label="详情页图片" prop="detailImage" class="flex-1">
              <div style="width: 120px;">
                <el-upload class="avatar-uploader" action="/api/file/upload-course-img" :show-file-list="false"
                  accept="image/jpeg,image/png,image/webp"
                  :on-success="(res) => handleUploadSuccess(res, 'detailImage')" :before-upload="beforeUpload">
                  <img v-if="formData.detailImage" :src="formData.detailImage" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </el-form-item>
          </div>
          <div class="flex-x">
            <el-form-item label="课时数量" prop="hours" class="flex-1">
              <el-input-number v-model="formData.hours" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="发布" prop="enabled" class="flex-1">
              <el-switch v-model="formData.enabled"></el-switch>
              <span class="text-gray-500 block mt--4 font-11">发布后学生可见</span>
            </el-form-item>
            <el-form-item label="公开" prop="isPublic" class="flex-1">
              <el-switch v-model="formData.isPublic"></el-switch>
              <span class="text-gray-500 block mt--4 font-11">公开后全平台可见</span>
            </el-form-item>
            <el-form-item label="分享" prop="isShare" class="flex-1">
              <el-switch v-model="formData.isShare"></el-switch>
              <span class="text-gray-500 block mt--4 font-11">分享后平台其他学校可复制</span>
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>

    <TagSelect ref="tagSelect" @change="handleTagsChange" />
  </div>
</template>

<script>
import api from '@/common/api';
import { DEFAULT_TABLE_CUSTOM_CONFIG } from "@/common/constants";
import Editor from "@/components/admin/Editor.vue";
import TagSelect from '@/components/admin/TagSelectDialog.vue';

export default {
  name: 'CourseList',
  components: {
    Editor,
    TagSelect
  },
  data() {
    return {
      tableCustomConfig: DEFAULT_TABLE_CUSTOM_CONFIG,
      // List data
      dataList: [],
      currentRow: {},
      loading: false,
      total: 0,
      query: {
        keyword: '',
        currentPage: 1,
        limit: 10
      },

      // Dialog data
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        courseName: '',
        description: '',
        listImage: '',
        detailImage: '',
        hours: 0,
        enabled: false,
        isPublic: false,
        isShare: false,
      },
      rules: {
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入课程简介', trigger: 'blur' }
        ],
        listImage: [
          { required: false, message: '请上传列表页图片', trigger: 'change' }
        ],
        detailImage: [
          { required: false, message: '请上传详情页图片', trigger: 'change' }
        ],
        hours: [
          { required: true, message: '请输入课时数量', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getDataList();
  },
  methods: {
    // Get data list
    async getDataList() {
      try {
        this.loading = true;
        const { data } = await api.admin_getCourseList({
          currentPage: this.query.currentPage,
          limit: this.query.limit,
          keyword: this.query.keyword
        });
        this.dataList = data.data.records;
        this.total = data.data.total;
      } catch (error) {
        this.$message.error('获取课程列表失败');
      } finally {
        this.loading = false;
      }
    },

    // Handle pagination
    handleSizeChange(val) {
      this.query.limit = val;
      this.getDataList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getDataList();
    },
    handleTableCustom() {
      this.$refs.table?.openCustom()
    },
    handleEditTags(row) {
      this.currentRow = row
      const tagIds = row.tags?.map(it => it.id)
      this.$refs.tagSelect.open(tagIds)
    },
    async handleTagsChange(tagIds) {
      try {
        const data = {
          targetId: this.currentRow.id,
          targetType: 'course',
          tagIds
        }
        await api.admin_saveTagRel(data);
        this.$message.success('标签更新成功');
        this.getDataList();
      } catch (error) {
        this.$message.error('标签更新失败');
      }
    },

    // Handle CRUD operations
    handleAdd() {
      this.dialogTitle = '添加课程';
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑课程';
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该课程?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await api.admin_deleteCourse(row.id);
        this.$message.success('删除成功');
        this.getDataList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },
    async handleStatusChange(row, field) {
      try {
        await api.admin_saveCourse({
          id: row.id,
          [field]: row[field]
        });
        this.$message.success('状态更新成功');
      } catch (error) {
        row[field] = !row[field];
        this.$message.error('状态更新失败');
      }
    },

    // Form operations
    submitForm() {
      this.$refs.courseForm.validate(async (valid) => {
        if (valid) {
          try {
            await api.admin_saveCourse(this.formData);
            this.$message.success(this.formData.id ? '更新成功' : '添加成功');
            this.dialogVisible = false;
            this.getDataList();
          } catch (error) {
            this.$message.error(this.formData.id ? '更新失败' : '添加失败');
          }
        }
      });
    },
    resetForm() {
      this.$refs.courseForm?.resetFields();
      this.formData = {
        courseName: '',
        description: '',
        listImage: '',
        detailImage: '',
        hours: 0,
        enabled: true
      };
    },

    // Upload handlers
    handleUploadSuccess(res, field) {
      console.log(res)
      if (res.status === 200) {
        this.formData[field] = res.data;
        this.$message.success('上传成功');
      } else {
        this.$message.error('上传失败');
      }
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },

    // Filter operations
    filterByKeyword() {
      this.query.currentPage = 1;
      this.getDataList();
    },

    // Utils
    formatDate(date) {
      return date
    },
    handleManageSections(row) {
      this.$router.push({
        name: 'admin-course-section-list',
        query: { courseId: row.id }
      });
    },
    handleManageLessons(row) {
      this.$router.push({
        name: 'admin-lesson-list',
        query: { courseId: row.id }
      });
    }
  }
};
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}
</style>
